package com.aletto.general_store.utils.watchers;

import android.widget.CheckBox;
import android.widget.TextView;

import androidx.collection.ArrayMap;

import java.util.Collection;
import java.util.Map;

public class ContentSubject implements Subject {

    private OnEnableListener mCallback;

    private final Map<Observer, Boolean> mObservedMap = new ArrayMap<>();

    private boolean mPreWatchResult = false;

    public ContentSubject add(TextView textView, IRule rule) {
        TextViewObserver textViewObserver = new TextViewObserver(textView instanceof CheckBox ? (CheckBox) textView : textView);
        return add(textViewObserver, rule);
    }

    public ContentSubject add(Observer observer, IRule rule) {
        observer.bind(this, rule);
        mObservedMap.put(observer, rule.validation());
        return this;
    }


    @Override
    public void validation(Observer target, boolean result) {
        mObservedMap.put(target, result);
        Collection<Boolean> values = mObservedMap.values();

        if (mCallback != null) {
            // 每次存入时获取结果
            boolean watchResult = !values.contains(Boolean.FALSE);
            // 当前结果与上次不同时，即为
            if (watchResult != mPreWatchResult) {
                mPreWatchResult = watchResult;
                mCallback.enable(watchResult);
            }
        }
    }


    public void setOnEnableListener(OnEnableListener callback) {
        this.mCallback = callback;
    }


    public interface OnEnableListener {
        void enable(boolean enable);
    }

}
